package com.jwong.grpc.customheader;

import com.jwong.grpc.helloworld.GreeterGrpc;
import com.jwong.grpc.helloworld.HelloReply;
import com.jwong.grpc.helloworld.HelloRequest;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.ServerInterceptors;
import io.grpc.stub.StreamObserver;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class CustomHeaderServer {

    private Server server;

    public void start() throws IOException {

        int port = 9000;

        server = ServerBuilder
            .forPort(port)
            .addService(ServerInterceptors.intercept(new GreeterServiceImpl(), new HeaderServerInterceptor()))
            .build()
            .start()
        ;

        System.out.println("Server start.....listen on " + port);

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                CustomHeaderServer.this.stop();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }));

    }

    public void stop() throws InterruptedException {
        server.shutdownNow().awaitTermination(30, TimeUnit.SECONDS);
    }

    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }

    public static class GreeterServiceImpl extends GreeterGrpc.GreeterImplBase {

        @Override
        public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
            System.out.println("request = " + request);
            String replyMessage = "Hello " + request.getName();
            HelloReply helloReply = HelloReply.newBuilder().setMessage(replyMessage).build();
            responseObserver.onNext(helloReply);
            responseObserver.onCompleted();
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        CustomHeaderServer customHeaderServer = new CustomHeaderServer();
        customHeaderServer.start();
        customHeaderServer.blockUntilShutdown();
    }

}
